﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventDemo1
{
    class Program
    {
        static void Main(string[] args)
        {
            Publishser pub = new Publishser();
            Subscriber sub = new Subscriber();

            pub.NumberChanged += new NumberChangeEventHandler(sub.OnNumberChanged);
            //应该通过DoSomething()来触发事件
            pub.DoSomething();
            //也可以这样直接调用，对委托变量的不恰当使用
            //pub.NumberChanged(100);
        }

        //定义委托
        public delegate void NumberChangeEventHandler(int count);

        //定义发布者
        public class Publishser
        {
            private int count;
            //声明委托变量
            //public NumberChangeEventHandler NumberChanged;
            //声明一个事件
            public event NumberChangeEventHandler NumberChanged;

            public void DoSomething()
            {
                //在这里完成一些工作

                if (NumberChanged != null)
                {
                    count++;
                    NumberChanged(count);
                }
            }
        }

        //定义事件订阅者
        public class Subscriber
        {
            public void OnNumberChanged(int count)
            {
                Console.WriteLine("Subscriber notified: count = {0}", count);
            }
        }

    }
}
